from flask import Flask
from flask import render_template
from flask import url_for
from flask import jsonify
from flask import request, json
from werkzeug.utils import secure_filename

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/user/<name>')
def username(name):
    if name == "张三":
        name = "这是张三"
    else:
        name = "这不是张三，而是" + name
    return '<h1>hello,%s</h>' % name


@app.route('/user/show')
def user():
    users = [['张三', '男', '重庆'],
             ['李四', '，女', '河南']]
    return render_template("user.html", list=users)


@app.route('/url/')
def redirect_to_url():
    return url_for('post_show', post_id=666)


@app.route('/post/<int:post_id>')
def post_show(post_id):
    return 'post ID : %d' % post_id


@app.route('/getJson')
def getJson():
    data = {
        "name": "张三",
        "sex": "男",
        "age": 20,
        "address": "xxxx"
    }
    return jsonify(data)


# get请求
@app.route('/login', methods=['GET', 'POST'])
def login():
    data = "无数据"
    if request.method == 'GET':
        print("当前请求的方法是GET")
        username = request.args.get("username")
        address = request.values.get("address")

        data = {
            "username": username,
            "address": address
        }
    elif request.method == 'POST':
        print("当前请求的方法是POST")
        username = request.args.get("username")
        address = request.values.get("address")

        data = {
            "username": username,
            "address": address
        }
        print(data)
        return jsonify(data)


# 传递json
@app.route('/passJson', method=['POST'])
def passJson():
    data = json.loads(request.get_data(as_text=True))
    return jsonify(data)


# 文件上传
# 步骤一  创建一个带静态文件的路由
@app.route('/upload/index')
def toUploadPage():
    return render_template('upload2.html')


# 静态文件中有文件上传功能，点击该1功能上传文件
@app.route('/upload')
def upload():
    if request.method == 'POST':
        file = request.files['file']
        print(request.fileds)

        file.save(secure_filename(file.filename))
        return "文件上传成功"
    else:
        return render_template('upload2.html')


if __name__ == '__main__':
    app.debug = True
    app.run()
